package cn.tedu.store.order.webapi.service.impl;

import cn.tedu.store.commons.ex.ServiceException;
import cn.tedu.store.commons.pojo.order.dto.CartAddNewDTO;
import cn.tedu.store.commons.pojo.order.dto.CartUpdateDTO;
import cn.tedu.store.commons.pojo.order.entity.Cart;
import cn.tedu.store.commons.pojo.order.vo.CartStandardVO;
import cn.tedu.store.commons.web.JsonPage;
import cn.tedu.store.commons.web.ServiceCode;
import cn.tedu.store.order.service.ICartService;
import cn.tedu.store.order.webapi.mapper.CartMapper;
import cn.tedu.store.order.webapi.security.LoginPrincipal;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Slf4j
@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    @Override
    public void addCart(CartAddNewDTO cartAddNewDTO) {
        log.debug("[新增购物车]业务 参数:{}",cartAddNewDTO);
        int rows = 0;
        Long userId = getUserId();
        //判断购物车中是否已经存在相同商品
        Cart cart = cartMapper.selectExistsCart(userId, cartAddNewDTO.getSkuId());
        if(cart == null) {//不存在,直接新增
            Cart newCart = new Cart();
            BeanUtils.copyProperties(cartAddNewDTO,newCart);
            newCart.setUserId(userId);
            rows = cartMapper.addNew(newCart);
        }else {//存在,只增加商品数量
            cart.setQuantity(cart.getQuantity()+cartAddNewDTO.getQuantity());
            rows = cartMapper.updateQuantityById(cart);
        }
        if(rows != 1) {
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }

    }

    @Override
    public JsonPage<CartStandardVO> listCarts(Integer pageNum, Integer pageSize) {
        log.debug("[查询购物车列表]业务 参数:{},{}",pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        return JsonPage.restPage(cartMapper.listByUserId(getUserId()));
    }

    @Override
    public void removeCart(Long[] ids) {
        log.debug("[删除购物车业务] 参数:{}", Arrays.toString(ids));
        int rows = cartMapper.deleteByIds(ids);
        if(rows != ids.length){
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
    }

    @Override
    public void removeAllCarts() {
        log.debug("[清空购物车]");
        int rows = cartMapper.deleteByUserId(getUserId());
        log.debug("已清理{}个购物车项!",rows);
    }

    @Override
    public void removeUserCarts(Cart cart) {
        cartMapper.deleteByUserIdAndSkuId(cart);
    }

    @Override
    public void updateQuantity(CartUpdateDTO cartUpdateDTO) {
        log.debug("[修改购物车商品数量] 参数:{}", cartUpdateDTO);
        Cart cart = new Cart();
        BeanUtils.copyProperties(cartUpdateDTO, cart);
        cartMapper.updateQuantityById(cart);
    }

    private LoginPrincipal getLoginPrincipal(){
        UsernamePasswordAuthenticationToken authenticationToken=
                (UsernamePasswordAuthenticationToken)
                        SecurityContextHolder.getContext().getAuthentication();
        if(authenticationToken == null){
            throw new ServiceException(
                    ServiceCode.ERR_UNAUTHORIZED,"您没有登录!");
        }
        LoginPrincipal loginPrincipal = (LoginPrincipal)authenticationToken.getPrincipal();
        return loginPrincipal;
    }
    //获取当前登录与用户id
    private Long getUserId(){
        return getLoginPrincipal().getId();
    }

}
